using DA.AnimGraph;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

namespace DA.AnimGraph.Editor {
    internal class HierarchyPaneService : Service {
        public void OpenGraphByUuid(AUID uuid) {
            (provider as HierarchyPane).OpenGraphByUuid(uuid);
        }
    }


    internal class HierarchyPane : ContextPaneBase {

        HandleKeeper<AGAHandle_Root> rootHK;
        List<HandleKeeper<AGAHandle_Graph>> graphHKs;

        private Button addGraphButton;
        private ScrollView hierarchyContainer;
        List<ClickedLabel> hierarchyLabels;
        AUID selectedGraph;

        internal HierarchyPane(ContextPaneBase parent) : base(parent) {
            hierarchyLabels = new();
            addGraphButton = new Button();
            addGraphButton.text = "+";
            addGraphButton.clicked += () => {
                rootHK.handle.NewGraph();
            };
            hierarchyContainer = new ScrollView();
            hierarchyContainer.style.flexGrow = 1;

        }

        protected override void OnSetHandle(AGAHandleBase handle) {
            Debug.Assert(handle is AGAHandle_Root || handle == null);
            if (handle == null) {
                rootHK = default;
                return;
            }
            rootHK = new HandleKeeper<AGAHandle_Root>(handle as AGAHandle_Root);
        }

        void GetGraphHandles() {
            if (graphHKs != null) {
                graphHKs.Clear();
                graphHKs = null;
            }

            var graphsUuid = rootHK.handle.GetAllGraphsUuid();
            graphHKs = new(graphsUuid.Length);
            foreach (var uuid in graphsUuid) {
                graphHKs.Add(rootHK.handle.GetChildHandle(uuid).ToKeeper<AGAHandle_Graph>());
            }
        }

        protected override void OnClearUI() {
            ageEnv.serviceManager.RemoveService<HierarchyPaneService>(this);
            hierarchyLabels.Clear();
            Clear();
        }

        protected override void OnDrawUI() {
            ageEnv.serviceManager.AddService<HierarchyPaneService>(this);

            var title = new PaneTitle("Hierarchy") { name = "pane_title" };
            Add(title);

            Add(addGraphButton);
            Add(hierarchyContainer);

            if (rootHK.isDirty) {
                GetGraphHandles();
                rootHK.ClearDirty();
            }
            // graph 列表
            RebuildHierarchyLabels();


            // 默认打开第一个图
            OpenGraphByIndex(0);
            // if (!selectedGraph.isValid) {
            //     selectedGraph = graphHKs[0].uuid;
            // }
            // ageContext.serviceManager.GetService<OpenGraphService>().OpenGraph(selectedGraph);
        }

        protected override void OnUpdateUI() {
            if (rootHK.isDirty) {
                GetGraphHandles();
                rootHK.ClearDirty();

                RebuildHierarchyLabels();
            }
        }

        public void RebuildHierarchyLabels() {
            hierarchyLabels.Clear();
            hierarchyContainer.Clear();
            for (int i = 0; i < graphHKs.Count; i++) {
                var hk = graphHKs[i];
                if (hk.isDirty) {
                    hk.ClearDirty();
                }
                var clickedLabel = new ClickedLabel(hk.handle.name) {
                    name = $"graph_{i}",
                    style = {
                        height = 25,
                    }
                };
                int graphIndex = i;
                clickedLabel.onDoubleClick += evt => { OpenGraphByIndex(graphIndex); };
                clickedLabel.AddMenuItem("重命名", () => { RenameGraph(graphIndex); });
                clickedLabel.AddMenuItem("复制名称到剪贴板", () => EditorGUIUtility.systemCopyBuffer = clickedLabel.text);
                clickedLabel.AddMenuItem("删除", () => { DeleteGraph(graphIndex); });
                clickedLabel.enableMenu = true;
                hierarchyLabels.Add(clickedLabel);
                hierarchyContainer.Add(clickedLabel);

                // 当前选中的显示上突出一下
                if (selectedGraph == hk.uuid) {
                    clickedLabel.style.unityFontStyleAndWeight = FontStyle.BoldAndItalic;
                } else {
                    clickedLabel.style.unityFontStyleAndWeight = FontStyle.Normal;
                }

                graphHKs[i] = hk;
            }
        }
        public void OpenGraphByUuid(AUID uuid) {
            if (uuid == selectedGraph) {
                // 是当前选择的不进行操作
                return;
            }
            selectedGraph = uuid;
            ageContext.serviceManager.GetService<OpenGraphService>().OpenGraph(selectedGraph);

            // 当前选中的显示上突出一下
            for (int i = 0; i < graphHKs.Count; i++) {
                if (graphHKs[i].uuid == uuid) {
                    hierarchyLabels[i].style.unityFontStyleAndWeight = FontStyle.BoldAndItalic;
                } else {
                    hierarchyLabels[i].style.unityFontStyleAndWeight = FontStyle.Normal;
                }
            }
            // 清除Inspector的显示内容
            ageContext.serviceManager.GetService<ShowInspectorService>().ClearInspector();
        }
        void OpenGraphByIndex(int index) {
            var uuid = graphHKs[index].uuid;
            OpenGraphByUuid(uuid);
        }
        void DeleteGraph(int index) {
            var uuid = graphHKs[index].uuid;
            if (uuid == selectedGraph) {
                // 是当前选择的不进行操作
                D.E("不能删除当前打开的graph");
                return;
            }
            rootHK.handle.DeleteGraph(uuid);
        }

        void RenameGraph(int index) {
            var uuid = graphHKs[index].uuid;
            var window = DialogWindow.ShowWindow("重命名", 400, 40);
            string newName = graphHKs[index].handle.name;

            var pack = new TextField("新名称") {
                value = newName
            };
            window.UseTemplate_2Button("确定", "取消", pack, (answer) => {
                if (answer == 1) {
                    rootHK.handle.RenameGraph(uuid, pack.value);
                }
            });
        }

    }
}
